<template>
  <v-app class="bg-gray">
    <!--        不显示底部菜单时 paddingbottom应该为0，不这样写message界面底部有问题，-->
    <!--        :class="{'pb-0':!showBottomNav,'pt-56':chatVue,'pt-0':mineVue}"-->
    <v-content>
      <!--            水平居中-->
      <u-row justify-center fill-height>

        <keep-alive>
          <v-flex v-if="$route.meta.keepAlive" xs12 sm6 md4>
            <router-view></router-view>
          </v-flex>
        </keep-alive>
        <v-flex v-if="!$route.meta.keepAlive" xs12 sm6 md4>
          <router-view></router-view>
        </v-flex>
      </u-row>
      <!--<div v-for="i in 100">
          123
      </div>-->
    </v-content>
    <v-bottom-navigation v-if="showBottomNav" app grow :value="$route.name" color="white">
      <!--<v-btn color="teal" flat value="talkList" to="/">
          <span>主页</span>
          <v-icon>home</v-icon>
      </v-btn>-->
      <!--<v-btn color="teal" text :value="$routerName.match" to="/">
        <span>匹配</span>
        <v-icon>favorite</v-icon>
      </v-btn>-->

      <v-btn color="teal" text :value="$routerName.talk" to="/talk">
        <span>处对象<span v-if="unreadNotifies.length" class="error--text">({{unreadNotifies.length}})</span></span>
        <v-icon>deck</v-icon>
      </v-btn>

      <template v-if="loginUser">
        <!--<v-btn color="teal" text :value="$routerName.chat" to="/chat">
          <span>消息<span v-if="chats.length" class="error&#45;&#45;text">({{chats.length}})</span></span>
          <v-icon>question_answer</v-icon>
        </v-btn>-->

        <v-btn color="teal" text :value="$routerName.mine" to="/user/mine">
          <span>我的</span>
          <v-icon>account_box</v-icon>
        </v-btn>
      </template>
    </v-bottom-navigation>
  </v-app>
</template>


<script lang="ts">
  import {Vue, Component, Watch} from 'vue-property-decorator'
  import {namespace} from "vuex-class"
  import User from "@/model/User"
  import Stomp from 'stompjs'
  import SockJS from 'sockjs-client'
  import Notify from "@/model/Notify"
  import Chat from "@/model/Chat"
  import UnreadNotify from "@/model/UnreadNotify"

  const chatModule = namespace('chat')
  const userModule = namespace('user')
  const talkModule = namespace('talk')
  const notifyModule = namespace('notify')

  @Component
  export default class AppVue extends Vue {
    stompClient: any = null
    @chatModule.State('chats') chats: Chat []
    @userModule.State('user') loginUser: User
    @talkModule.State('inputContentFocus') inputContentFocus: boolean
    @notifyModule.State('unreadNotifies') unreadNotifies: UnreadNotify[]
    drawer: boolean = false

    created() {
      //初始的时候查询，以后每次推送也都可以更新，等于messageList页面，这个是先加载出来的时候，进入那个页面的时候都是只读操作
      this.connect()
      //开启计时器，每30秒检测一次websocket是否断开，如果断开则重连
      setInterval(() => {
        this.connect()
      }, 30 * 1000)
    }

    @Watch('loginUser')
    loginUserWatch() {
      if (this.loginUser) {
        this.connect()
      }
    }

    get chatVue() {
      return this.loginUser && this.$route.name === this.$routerName.chat
    }

    get mineVue() {
      return this.loginUser && this.$route.name === this.$routerName.mine
    }

    // 已登录才显示底部导航栏
    get showBottomNav() {
      return !this.inputContentFocus && ((this.$route.name === this.$routerName.match
        || this.$route.name === this.$routerName.chat
        || this.$route.name === this.$routerName.mine
        || this.$route.name === this.$routerName.talk))
    }

    connect() {
      // 已登录才连接websocket
      if (this.loginUser && !(this.stompClient && this.stompClient.connected)) {
        // 建立连接对象
        const socket = new SockJS(this.$websocketUrl)
        // 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(socket)
        // 已登录，获取token
        const token = this.$token.get()
        // 定义客户端的认证信息,按需求配置
        const headers = {token}
        // 向服务器发起websocket连接
        this.stompClient.connect(headers, () => {
          //成功连接后查询chat，可能存在断开后丢失的内容
          this.$store.dispatch('chat/getChats')
          // 订阅消息
          this.stompClient.subscribe('/user/queue/notifications', (notifyJson: any) => {
              const notify: Notify = JSON.parse(notifyJson.body)
              // @ts-ignore
              if (notify.type === this.$const.notifyType.remove_chat) {
                this.$store.dispatch('chat/getChats')
              } else if (notify.type === this.$const.notifyType.message) {
                this.$store.commit('chat/pushChat', notify.chat)
                // if ([this.$const.chatType.MATCH_UNLOCKED, this.$const.chatType.MATCH_CHAT].includes(notify.type)) {
                Notification.requestPermission(permission => {
                  if (permission == 'granted') {
                    navigator.serviceWorker.ready.then(registration => {
                      //如果当前的chat就是这个chat则不需要跳转，只需要添加新的message就行
                      let chat: Chat = this.chats.find(item => item.id === notify.chat.id)
                      //目前进行到了匹配成功后，发起聊天后，每次都跳转你的问题，需要添加判断，如果当前在mess页面，
                      // 并且当前chat为此chat，则不跳转
                      //还有个问题，匹配成功后，聊天结束后，解除匹配后，和其他喜欢的，喜欢你的关系怎么处理
                      /*if (chat) {
                        this.$router.push('/message/' + chat.id)
                      }*/
                      var title = '清池'
                      const options: NotificationOptions = {
                        body: '来消息了，快去聊天吧！',
                        icon: this.$imgUrl + notify.chat.img,
                        tag: 'pwa-starter',
                        renotify: true,
                        timestamp: new Date().getTime(),
                        data: chat || null
                      }
                      registration.showNotification(title, options)
                    })
                  }
                })
              } else if (notify.type === this.$const.notifyType.comment) {
                this.$store.commit('notify/addUnreadNotifies', notify.unreadNotify)
              }
            }
          )
        })
      }
    }
  }
</script>

<style>
  /*解决底部导航栏按钮太小bug*/
  .v-item-group.v-bottom-navigation .v-btn.v-size--default {
    height: inherit;
  }
</style>
